/**   
 * @Title: LoginAct.java 
 * @Package com.esun.rabbit2.viewer 
 * @Description: (登陆用activity) 
 * @author City Jiangsy@500wan.com   
 * @date 2011-6-8 下午01:40:01  
 * copy right 深圳市易讯天空网络技术有限公司
 */
package com.esun.rabbit2.viewer;

import org.androidpn.client.Constants;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.esun.config.Config;
import com.esun.config.Key;
import com.esun.config.Language;
import com.esun.model.UserInfo;
import com.esun.network.ConnectionChangeReceiver;
import com.esun.rabbit2.communicaters.user.NewLoginCommunicater;
import com.esun.rabbit2.viewer.mainact.OptionAct;
import com.esun.rabbit2.viewer.mainact.mylotteryact.bindmobile.BindMobileUnBindAct;
import com.esun.ui.R;
import com.esun.util.EditTextInputUitl;
import com.esun.util.ViewerUtil;
import com.esun.util.ip.IpGetter;
import com.esun.util.log.EDebug;
import com.esun.util.magic.magic;
import com.esun.util.md5.MD5;

/**
 * @ClassName: LoginAct
 * @Description: (用户登陆activity)
 * @author City Jiangsy@500wan.com
 * @date 2011-6-8 下午01:40:01
 * 
 */
public class LoginAct extends Activity implements OnClickListener, TextView.OnEditorActionListener, OnCheckedChangeListener {
	/** Called when the activity is first created. */
	private Button btnLogin; // 登錄按鈕
	private Button btnRegist; // 注册..
	private ImageButton btnBack; // 返回..
	private Button btnCleanUserName; // 清空用户名..
	private Button btnCleanUserPass; // 清空密码..
	private CheckBox cbxSave; // 确定保存用户名和密码
	private CheckBox cbxAutoLogin;
	private EditText edtUserName; // 输入用户名
	private EditText edtUserPass; // 输入密码

	private Handler loginHandler;
	private final int LOGIN_SUCCEED = 1001;
	private final int LOGIN_FAIL = 1002;

	private ProgressDialog loginProgressDialog;
	private Dialog dialogLock;

	private String strUserName;
	private String strUserPass;
	private String serverMessage;
	private String strDBUserPass;
	private String strShortPass;
	private String strUserMobile;

	private String ip;
	private String versionName;
	private IpGetter ipGetter;
	private int resultState;

	private boolean isSaveUserData = false; // 标志位,是否保存用户名和密码
	private boolean isAutoLogin = false; // 标志位，是否自动登录
	private boolean isLoginSucceed = false;// 是否登陆成功

	private NewLoginCommunicater userCommunicater;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login_act);
		dataInit();
		uiInit();
		handlerInit();

	}

	// 数据初始化
	private void dataInit() {
		strUserName = UserInfo.getUserInfo().getUserName();
		strUserPass = UserInfo.getUserInfo().getUserPwd();
		isSaveUserData = UserInfo.getUserInfo().isSaveData();
		isAutoLogin = UserInfo.getUserInfo().isAutoLogin();

		EDebug.o(this, "user name = " + strUserName + " user pwd = " + strUserPass + " is save = " + isSaveUserData + " is auto = " + isAutoLogin);

		if (isSaveUserData && !UserInfo.getUserInfo().getUserPwd().equals(Config.NULLMARK)) {
			strShortPass = Config.LEFT_BR + Config.LEFT_BR + Config.LEFT_BR + Config.LEFT_BR + Config.LEFT_BR + Config.LEFT_BR;
			strDBUserPass = UserInfo.getUserInfo().getUserPwd();
		} else {
			strShortPass = Config.NULLMARK;
			strDBUserPass = Config.NULLMARK;
		}

	}

	private void handlerInit() {
		loginHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case LOGIN_SUCCEED:
					UserInfo.getUserInfo().setInputPasswordTime();
					UserInfo.getUserInfo().setSaveData(isSaveUserData);
					UserInfo.getUserInfo().setAutoLogin(isAutoLogin);
					UserInfo.getUserInfo().setUserName(strUserName);
					UserInfo.getUserInfo().setUserPwd(strUserPass);
					UserInfo.getUserInfo().setNetWork(true);
					userCommunicater.updataUserInfo();
					loginProgressDialog.dismiss();
					Toast.makeText(LoginAct.this, UserInfo.getUserInfo().getUserName() + ",您已登录成功", Toast.LENGTH_SHORT).show();
					OptionAct.isLoginSucceed = true;

					if (resultState == 100) {
						startActivity(new Intent(LoginAct.this, BindMobileUnBindAct.class).putExtra(Key.KEY_MOBILENUM, strUserMobile).putExtra(Key.KEY_STATE, Config.NUM0));
					}
					setResult(RESULT_OK);
					LoginAct.this.finish();

					break;

				case LOGIN_FAIL:
					loginProgressDialog.dismiss();
					if (userCommunicater.getState() == 109) {
						ViewerUtil.showTipDialog(LoginAct.this, serverMessage, false);
					} else if (userCommunicater.getResultCode() == 1) {
						showLockDialog();
					} else if (userCommunicater.getResultCode() == 2 || userCommunicater.getResultCode() == 3) {
						ViewerUtil.showTipDialog(LoginAct.this, Language.MSG_IPLOCKED, false);
					} else {
						ViewerUtil.showTipDialog(LoginAct.this, "用户名或密码错误", false);
					}
					break;

				case Config.CONNECTION_FAIL:
					loginProgressDialog.dismiss();

					Toast.makeText(LoginAct.this, Language.STR_CONNECTIONFAIL.toString(), Toast.LENGTH_SHORT).show();
					break;

				default:
					break;
				}
			}

		};
	}

	private void showLockDialog() {
		if (dialogLock == null) {
			dialogLock = new Dialog(this, R.style.dialog);
		}
		dialogLock.getWindow().setContentView(R.layout.viewerutil_dialog_usernamelocked);
		OnClickListener listener = new OnClickListener() {

			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.viewerutildialogusernamelocked_btn_cancel:
					dialogLock.dismiss();
					break;

				case R.id.viewerutildialogusernamelocked_btn_submit:
					Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(Config.URL_UNLOCK));
					startActivity(intent);
					dialogLock.dismiss();
					break;

				default:
					break;
				}
			}
		};
		((Button) dialogLock.getWindow().findViewById(R.id.viewerutildialogusernamelocked_btn_cancel)).setOnClickListener(listener);
		((Button) dialogLock.getWindow().findViewById(R.id.viewerutildialogusernamelocked_btn_submit)).setOnClickListener(listener);
		((TextView) dialogLock.getWindow().findViewById(R.id.viewerutildialogusernamelocked_tv_msg)).setText(Language.MSG_ACCOUNTLOCKED);
		dialogLock.show();
	}

	// 子线程,登陆
	private void threadLogin() {
		new Thread() {
			@Override
			public void run() {
				super.run();
				try {
					if (userCommunicater == null) {
						userCommunicater = new NewLoginCommunicater();
					}
					String userIMEI;

					SharedPreferences sharedPre = LoginAct.this.getSharedPreferences(Config.CLIENT_PREFERENCES, Context.MODE_PRIVATE);
					userIMEI = sharedPre.getString(Constants.DEVICE_ID, Config.DEFAULT_LEAGUAGE_NUM);
					String useragent = android.os.Build.MODEL;
					String IMEI = magic.getIMEI(LoginAct.this);

					isLoginSucceed = userCommunicater.isLoginSucceed(strUserName, strUserPass, versionName, userIMEI, useragent, IMEI);
					serverMessage = userCommunicater.getServerMsg();

					if (isLoginSucceed) {
						Message msg = loginHandler.obtainMessage(LOGIN_SUCCEED, null);
						loginHandler.sendMessage(msg);
					} else {
						Message msg = loginHandler.obtainMessage(LOGIN_FAIL, null);
						loginHandler.sendMessage(msg);
					}

				} catch (Exception e) {
					Message msg = loginHandler.obtainMessage(Config.CONNECTION_FAIL, null);
					loginHandler.sendMessage(msg);
				}
			}
		}.start();
	}

	private void uiInit() {
		btnLogin = (Button) findViewById(R.id.loginact_btn_login);
		btnLogin.setOnClickListener(this);

		btnRegist = (Button) findViewById(R.id.loginact_btn_regist);
		btnRegist.setOnClickListener(this);

		btnBack = (ImageButton) findViewById(R.id.loginact_btn_back);
		btnBack.setOnClickListener(this);

		cbxSave = (CheckBox) findViewById(R.id.loginact_cbx_save);
		cbxSave.setOnCheckedChangeListener(this);
		cbxSave.setChecked(isSaveUserData);

		cbxAutoLogin = (CheckBox) findViewById(R.id.loginact_cbx_autologin);
		cbxAutoLogin.setOnCheckedChangeListener(this);
		cbxAutoLogin.setChecked(isAutoLogin);

		edtUserName = (EditText) findViewById(R.id.loginact_edt_userName);
		btnCleanUserName = (Button) findViewById(R.id.loginact_btn_claenUserNmae);
		edtUserName = new EditTextInputUitl(edtUserName, btnCleanUserName).getEditText();

		edtUserPass = (EditText) findViewById(R.id.loginact_edt_userPass);
		btnCleanUserPass = (Button) findViewById(R.id.loginact_btn_claenUserPass);
		edtUserPass = new EditTextInputUitl(edtUserPass, btnCleanUserPass).getEditText();

		edtUserName.setText(strUserName);
		edtUserPass.setText(strShortPass);

		loginProgressDialog = ViewerUtil.showProgressDialog(this, Language.STR_LOGING);

		ipGetter = new IpGetter(this);
		ip = ipGetter.getStrIp();
		EDebug.o(this, "本机ip: " + ip);
		try {
			versionName = this.getPackageManager().getPackageInfo("com.esun.ui", 0).versionName;
		} catch (Exception e) {
			versionName = Config.NULLMARK;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.loginact_btn_login:

			login();

			break;

		case R.id.loginact_btn_regist:

			startActivityForResult(new Intent(this, RegistWebAct.class), 0);

			break;

		case R.id.loginact_btn_back:
			LoginAct.this.finish();
			break;

		case R.id.loginact_btn_claenUserNmae:
			edtUserName.setText(Config.NULLMARK);
			break;

		case R.id.loginact_btn_claenUserPass:
			edtUserPass.setText(Config.NULLMARK);
			break;

		default:
			break;
		}

	}

	private void login() {
		if (!(edtUserName.getText().equals(null)) && !(edtUserPass.getText().equals(null)) && !(edtUserName.getText().toString().length() < 1) && !(edtUserPass.getText().toString().length() < 1)) {
			loginProgressDialog.show();
			strUserName = edtUserName.getText().toString().trim();
			// 我很纠结于此,关于密码的6位显示,如果有人注册密码"[[[[[["就真的扯了
			strUserPass = edtUserPass.getText().toString();
			if (strUserPass.equals(strShortPass)) {
				strUserPass = strDBUserPass;
			}
			// 验证md5处理
			if (strUserPass.length() != 32) {
				strUserPass = MD5.md5(strUserPass);
			}
			threadLogin();
		} else {
			if (edtUserName.getText().equals(null) || (edtUserName.getText().toString().length() < 1)) {
				ViewerUtil.showTipDialog(this, "请输入用户名", false);
			} else {
				ViewerUtil.showTipDialog(this, "请输入密码", false);
			}
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

		switch (buttonView.getId()) {

		case R.id.loginact_cbx_save:

			if (cbxSave.isChecked()) {
				isSaveUserData = true;
				EDebug.o(this, " save ");
			} else {
				cbxAutoLogin.setChecked(false);
				isAutoLogin = false;
				isSaveUserData = false;
			}
			break;

		case R.id.loginact_cbx_autologin:

			if (cbxAutoLogin.isChecked()) {
				cbxSave.setChecked(true);
				isSaveUserData = true;
				isAutoLogin = true;
			} else {
				isAutoLogin = false;
			}
			break;

		default:
			break;
		}

	}

	/** 隐藏软键盘 */
	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
		return true;
	}

	/** 更新数据库 用于用户名 密码 记住密码 自动登录标示位 */
	private void updateDBInfo(boolean isSaveName) {
		EDebug.o(this, "updateDBInfo");
		ContentValues cv = new ContentValues();

		if (isSaveUserData) {
			cv.put(Key.KEY_SAVE, Config.NUM1);
			if (isSaveName) {
				cv.put(Key.KEY_NAME, strUserName);
			}
			cv.put(Key.KEY_PASSWORD, strUserPass);
		} else {
			cv.put(Key.KEY_SAVE, Config.NUM0);
			cv.put(Key.KEY_PASSWORD, Config.NULLMARK);
		}
		if (isAutoLogin) {
			cv.put(Key.KEY_AUTOLOGIN, Config.NUM1);
		} else {
			cv.put(Key.KEY_AUTOLOGIN, Config.NUM0);
		}

		SQLiteDatabase db = this.openOrCreateDatabase(Key.KEY_DB_ARABBIT2, MODE_PRIVATE, null);
		db.update(Key.KEY_USERS, cv, "_id=?", new String[] { Config.NUM1 });
		db.close();
	}

	@Override
	protected void onPause() {
		super.onPause();
		// 退出时保存当前的状态
		updateDBInfo(isLoginSucceed);
		this.unregisterReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver());
	}

	@Override
	protected void onResume() {
		super.onResume();
		this.registerReceiver(ConnectionChangeReceiver.getConnectionChangeReceiver(), ConnectionChangeReceiver.getIntentFilter());
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		resultState = resultCode;

		switch (resultCode) {
		case 100:
			loginProgressDialog.show();
			Bundle bundle = data.getExtras();

			strUserName = bundle.getString(Key.KEY_USERNAME);
			strUserPass = bundle.getString(Key.KEY_PASSWORD);
			strUserMobile = bundle.getString(Key.KEY_MOBILENUM);
			edtUserName.setText(strUserName);
			edtUserPass.setText(strUserPass);

			EDebug.o(this, "edt user pass content = " + edtUserPass.getText().toString());

			threadLogin();

			break;
		}
	}

}
